package com.example.onlineanswer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlineanswer.common.annotation.RequiresLogin;
import com.example.onlineanswer.common.api.CommonResult;
import com.example.onlineanswer.model.entity.Question;
import com.example.onlineanswer.model.entity.QuestionType;
import com.example.onlineanswer.model.vo.QuestionVO;
import com.example.onlineanswer.service.QuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 题目管理控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "题目管理接口")
@RequestMapping("/api/questions")
public class QuestionController {

    private final QuestionService questionService;

    @ApiOperation("分页查询题目列表")
    @GetMapping("/page")
    public CommonResult<IPage<QuestionVO>> pageQuestionList(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("竞赛ID") @RequestParam(required = false) Long contestId,
            @ApiParam("竞赛名称") @RequestParam(required = false) String contestTitle,
            @ApiParam("题目类型ID") @RequestParam(required = false) Integer typeId,
            @ApiParam("难度") @RequestParam(required = false) Integer difficulty,
            @ApiParam("状态") @RequestParam(required = false) Integer status,
            @ApiParam("关键词") @RequestParam(required = false) String keyword) {
        Page<QuestionVO> page = new Page<>(pageNum, pageSize);
        IPage<QuestionVO> result = questionService.pageQuestionList(page, contestId, contestTitle, typeId, difficulty, status, keyword);
        return CommonResult.success(result);
    }

    @ApiOperation("获取题目详情")
    @GetMapping("/{id}")
    public CommonResult<QuestionVO> getQuestionDetail(
            @ApiParam("题目ID") @PathVariable Long id) {
        QuestionVO question = questionService.getQuestionDetailById(id);
        if (question == null) {
            return CommonResult.failed("题目不存在");
        }
        return CommonResult.success(question);
    }

    @ApiOperation("创建题目")
    @PostMapping
    public CommonResult<Long> createQuestion(
            @ApiParam("题目信息") @Valid @RequestBody Question question) {
        Long id = questionService.createQuestion(question);
        return CommonResult.success(id, "创建成功");
    }

    @ApiOperation("更新题目")
    @PutMapping("/{id}")
    public CommonResult<Boolean> updateQuestion(
            @ApiParam("题目ID") @PathVariable Long id,
            @ApiParam("题目信息") @Valid @RequestBody Question question) {
        boolean success = questionService.updateQuestion(id, question);
        return success ? CommonResult.success(true, "更新成功") : CommonResult.failed("更新失败");
    }

    @ApiOperation("删除题目")
    @DeleteMapping("/{id}")
    public CommonResult<Boolean> deleteQuestion(
            @ApiParam("题目ID") @PathVariable Long id) {
        boolean success = questionService.deleteQuestion(id);
        return success ? CommonResult.success(true, "删除成功") : CommonResult.failed("删除失败");
    }

    @ApiOperation("获取所有题目类型")
    @GetMapping("/types")
    public CommonResult<List<QuestionType>> getAllQuestionTypes() {
        List<QuestionType> types = questionService.getAllQuestionTypes();
        return CommonResult.success(types);
    }

    @ApiOperation("批量导入题目")
    @PostMapping("/import")
    public CommonResult<Integer> batchImportQuestions(
            @ApiParam("竞赛ID") @RequestParam Long contestId,
            @ApiParam("题目列表") @Valid @RequestBody List<Question> questions) {
        int count = questionService.batchImportQuestions(contestId, questions);
        return CommonResult.success(count, "成功导入" + count + "道题目");
    }

    @ApiOperation("审核题目")
    @PutMapping("/{id}/review")
    @RequiresLogin
    public CommonResult<Boolean> reviewQuestion(
            @ApiParam("题目ID") @PathVariable Long id,
            @ApiParam("审核状态 (1: 通过, 2: 拒绝)") @RequestParam Integer status,
            @ApiParam("审核人ID") @RequestParam Long reviewerId) {
        if (status != 1 && status != 2) {
            return CommonResult.failed("无效的审核状态");
        }
        boolean success = questionService.reviewQuestion(id, status, reviewerId);
        return success ? CommonResult.success(true, "审核成功") : CommonResult.failed("审核失败");
    }

    @ApiOperation("下载题目导入模板")
    @GetMapping("/template/download")
    public ResponseEntity<Resource> downloadTemplate() {
        try {
            // 调用服务层方法动态生成模板
            Resource resource = questionService.generateQuestionImportTemplate();
            
            // 设置响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=question_import_template.xlsx")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(resource);
        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.notFound().build();
        }
    }

    @ApiOperation("上传Excel导入题目")
    @PostMapping("/import/excel")
    public CommonResult<Integer> importQuestionsByExcel(
            @ApiParam("竞赛ID") @RequestParam Long contestId,
            @ApiParam("Excel文件") @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("文件不能为空");
        }
        
        try {
            // 解析Excel文件并导入题目
            int count = questionService.importQuestionsFromExcel(contestId, file);
            return CommonResult.success(count, "成功导入" + count + "道题目");
        } catch (Exception e) {
            log.error("导入题目失败", e);
            return CommonResult.failed("导入失败: " + e.getMessage());
        }
    }
} 